package iec104tcp;


import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import model.ModusTable;
import service.ModusTableService;
import wei.yigulu.iec104.annotation.AsduType;
import wei.yigulu.iec104.apdumodel.Apdu;
import wei.yigulu.iec104.asdudataframe.ShortFloatWithTimeType;
import wei.yigulu.iec104.asdudataframe.ShortIntegerWithTimeType;
import wei.yigulu.iec104.asdudataframe.typemodel.InformationBodyAddress;
import wei.yigulu.iec104.nettyconfig.Iec104MasterBuilder;
import wei.yigulu.netty.BaseProtocolBuilder;

import java.util.List;
import java.util.Map;

/**
 * 带时间有品质位的短浮值
 *
 * @author 修唯xiuwei
 * @version 3.0
 */
@EqualsAndHashCode(callSuper = true)
@AsduType(typeId = 36)
@NoArgsConstructor
@Slf4j
public class HandelShortFloatWithTime extends ShortFloatWithTimeType {

	ModusTableService modusTableService = ModusTableService.getInstance();


	@Override
	public byte[][] handleAndAnswer(Apdu apdu) throws Exception {
		apdu.getLog().trace("----------处理带时标短浮值值数据---------");
		BaseProtocolBuilder builder = apdu.getIec104Builder();
		if (builder != null && builder instanceof Iec104MasterBuilder) {
			//所有master 视为统一的 处理逻辑---存入数据池
			Map<Integer, ModusTable> dataPoint = (Map<Integer, ModusTable>) builder.getConfigInfoMap().get("ModusTable");
			HandelShortFloatWithTime handelShortFloatWithTime = (HandelShortFloatWithTime) apdu.getAsdu().getDataFrame();
			List<InformationBodyAddress> address = handelShortFloatWithTime.getAddresses();
			List<ShortFloatAndQualityWithTime> datas = handelShortFloatWithTime.getDatas();
			int i = 0;
			//存入共享服务端
			ModusTable modusTable;
			if (apdu.getAsdu().getVsq().getSq() == 0) {
				apdu.getLog().trace("------处理带时标短浮值单一寻址-----");
				for (ShortFloatAndQualityWithTime e : datas) {
					if(!e.getQuality().isGoodValue()){
						log.debug("品质描述异常");
						continue;
					}
					if (dataPoint.containsKey(address.get(i).getAddress())) {
						modusTable = dataPoint.get(address.get(i).getAddress());
						modusTableService.updateModusValue(modusTable.getIpIdentity(), modusTable.getId(), e.getValue() + "", e.getTime().toString());
					}
					i++;
				}
			} else if (apdu.getAsdu().getVsq().getSq() == 1) {
				apdu.getLog().trace("------处理带时标短浮值连续寻址-----");
				i = address.get(0).getAddress();
				for (ShortFloatAndQualityWithTime e : datas) {
					if(!e.getQuality().isGoodValue()){
						log.debug("品质描述异常");
						continue;
					}
					if (dataPoint.containsKey(i)) {
						modusTable = dataPoint.get(i);
						modusTableService.updateModusValue(modusTable.getIpIdentity(), modusTable.getId(), e.getValue() + "", e.getTime().toString());
					}
					i++;
				}
			}
		}
		return null;
	}


	@Override
	public String toString() {
		return super.toString();
	}


}
